package org.example.netty.server;

import org.example.netty.config.NettyEndpointConfig;
import org.example.netty.handler.message.MessageHandlerFactory;
import org.example.netty.mgt.ConnectionManager;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

public abstract class AbstractNettyEndpoint implements NettyEndpoint{

    public ConnectionManager getConnectionManager() {
        return connectionManager;
    }

    protected ConnectionManager connectionManager;
    protected MessageHandlerFactory messageHandlerFactory;
    protected ThreadPoolExecutor businessThreadPool;

    public AbstractNettyEndpoint( ConnectionManager connectionManager, MessageHandlerFactory messageHandlerFactory,ThreadPoolExecutor businessThreadPool) {
        this.connectionManager = connectionManager;
        this.messageHandlerFactory = messageHandlerFactory;
        this.businessThreadPool = businessThreadPool;
    }


    protected static class EndpointThreadFactory implements ThreadFactory {
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        EndpointThreadFactory(String name) {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                    Thread.currentThread().getThreadGroup();
            namePrefix = (name==null||"".equals(name)?"pool-":name) +
                    poolNumber.getAndIncrement() +
                    "-thread-";
        }

        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                    namePrefix + threadNumber.getAndIncrement(),
                    0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }

}
